/**
 * 计算总价
 * @param cartArr
 * @param $pageName
 */
$.sumAmount = function(cartArr, $pageName){
    var $sumAmount = 0;
    if (cartArr.length == 0)
    {
        $('.cart').addClass('hidden');
    } else {
        for (v in cartArr)
        {
            $sumAmount = $sumAmount + (cartArr[v][2]*cartArr[v][1]);
        }
    }

    if ($pageName == 'cart')
    {
        if(cartArr.length > 0)
        {
            $('.card').addClass('hidden');
            $('.media-list').removeClass('hidden');
        } else {
            $('.card').removeClass('hidden');
            $('.media-list').addClass('hidden');
        }
    }
    $('#sumAmount').text($sumAmount);
    if($sumAmount < 10)
    {
        $sumAmount += 1;
    }
    $('#pay-sumAmount').text($sumAmount);
}
/**
 * 删除列表项
 * @param id
 */
$.delCart = function(id, $pageName){
    var $cart = $.cookie('cart');
    if($cart && $cart != '')
    {
        var $cartArr = JSON.parse($cart);
        for (x in $cartArr)
        {
            if($cartArr[x][0] == id)
            {
                $cartArr.splice(x,1);
            }
        }
        $.sumAmount($cartArr,$pageName);
        if($cartArr.length == 0)
        {
            $.cookie('cart', null, { path: '/', expires: 0 });
        } else {
            var date = new Date();
            date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期
            $.cookie('cart', JSON.stringify($cartArr), { path: '/', expires: date });
        }
    }
}

/**
 * 刷新页面JS
 */
$.refreshJs = function($pageName) {
    var $cart = $.cookie('cart');
    if ($cart)
    {
        var cartArr = JSON.parse($cart);
        for (x in cartArr)
        {
            $('#goods-'+cartArr[x][0]+' .shop-add span').text(cartArr[x][2]);
            if(cartArr[x][2] > 0)
            {
                $('#goods-'+cartArr[x][0]+' .down').removeClass('hidden');
            }
        }
    }

    var $cartArr = [];
    if($cart && $cart != '')
    {
        $cartArr = JSON.parse($cart);
    }
    $.sumAmount($cartArr, $pageName);


    var COOKIE_NAME = 'storeID';
    $(".close-panel").click(function(){
        var date = new Date();
        date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期
        $.cookie(COOKIE_NAME, $(this).data('storeid'), { path: '/', expires: date });
        $.cookie('cart', null, { path: '/', expires: 0 });
    });
    var mySwiper1 = myApp.swiper('.swiper-1', {
        pagination:'.swiper-1 .swiper-pagination',
        spaceBetween: 50
    });

    $$('.swipeout').on('deleted', function () {
        var id = $$(this).find('span').data('id');
        $.delCart(id, $pageName);
    });
}

/**
 * cookie操作
 * @param $pageName
 */
$.mcookie = function($pageName){
    var n = 0;
    var id = 0;
    var amount = 0;
    var checkClick = false;
    //+
    $$(document).on('click','.plus', function (e) {
        var $cartArr = [];
        if (checkClick)
            return;
        checkClick = true;
        var $cart = $.cookie('cart');
        var $number = Number($(this).siblings('span').text());
        id = $(this).siblings('span').data('id');
        amount = $(this).siblings('span').data('amount');

        if ($number)
        {
            n = $number + 1;
            $(this).siblings('span').text(n);
        } else {
            n = 1;
            $(this).siblings('span').text(1);
            $(this).siblings('.down').removeClass('hidden');
        }
        //读取cookie
        if ($cart && $cart != '') {
            $cartArr = JSON.parse($cart);
            var i = 0;
            for (x in $cartArr)
            {
                if($cartArr[x][0] == id)
                {
                    i = 1;
                    $cartArr[x][1] = amount;
                    $cartArr[x][2] = n;
                }
            }
            if(!i)
            {
                $cartArr.push([id, amount, n]);
            }
        } else {
            $cartArr.push([id, amount, n])
        }
        $.sumAmount($cartArr, $pageName);
        var date = new Date();
        date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期
        $.cookie('cart', JSON.stringify($cartArr), { path: '/', expires: date });
        checkClick = false;
    });
    //-
    $$(document).on('click','.down', function (e) {
        var $cartArr = [];
        if (checkClick)
            return;
        checkClick = true;
        var $cart = $.cookie('cart');
        var $number = Number($(this).siblings('span').text());
        id = $(this).siblings('span').data('id');
        amount = $(this).siblings('span').data('amount');

        if ($number)
        {
            if($number - 1 == 0)
            {
                n = 0;
                $(this).addClass('hidden');
                $(this).siblings('span').text('');
                //删除对应数据
                myApp.swipeoutDelete($(this).parents('.swipeout'));

            } else {
                n = $number - 1;
                $(this).siblings('span').text($number - 1);
            }
        }
        //读取cookie
        if ($cart && $cart != '') {
            $cartArr = JSON.parse($cart);
            var i = 0;
            for (x in $cartArr)
            {
                if($cartArr[x][0] == id)
                {
                    if (n)
                    {
                        $cartArr[x][1] = amount;
                        $cartArr[x][2] = n;
                    } else {
                        $cartArr.splice(x,1);
                    }
                }
            }
        }
        $.sumAmount($cartArr, $pageName);
        if ($cartArr.length == 0)
        {
            $.cookie('cart', null, { path: '/', expires: 0 });
        } else {
            var date = new Date();
            date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期
            $.cookie('cart', JSON.stringify($cartArr), { path: '/', expires: date });
        }
        checkClick = false;
    });
}

$.getGoodsList = function ($pageName, $typeID) {
    var loading = false;
    var i = 1;
    var typeID = $typeID;
    var storeID = $$('#indexData').data('storeID');
    var token = $$('#indexData').data('token');
    var url = $$('#indexData').data('url');
    console.log(typeID);

    $$('.infinite-scroll').on('infinite', function () {

        // Exit, if loading in progress
        if (loading) return;

        // Set loading flag
        loading = true;

        // Emulate 1s loading
        $.ajax({
            type:"POST",
            url: url,
            data: {
                _token:token,
                page:i,
                typeID:typeID,
                storeID:storeID
            },
            dataType: "json",
            success:function(result){
                var str = "";
                if (result.code == 0) {
                    str = result.date;
                    //$$('.list-block ul').append(str);
                    //console.log($$(document).find('.list-block ul'));
                    $$(document).find('.list-block ul').append(str);
                    //$.mcookie($pageName);
                    loading = false;
                } else if (result.code == 1) {
                    // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    // Remove preloader
                    $$('.infinite-scroll-preloader').remove();
                    return;
                } else {
                    return false;
                }
            },
            error:function(){
                myApp.detachInfiniteScroll($$('.infinite-scroll'));
                // Remove preloader
                $$('.infinite-scroll-preloader').remove();
                loading = false;
                i--;
            }
        });
        i++;
    });
}
$.getOrderList = function ($pageName) {
    var loading = false;
    var i = 1;
    var url = $$('#orderData').data('url');

    $$('.infinite-scroll').on('infinite', function () {

        // Exit, if loading in progress
        if (loading) return;

        // Set loading flag
        loading = true;

        $$.ajax({
            url: url,
            method: 'POST',
            data: {
                page:i
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            dataType: 'json',
            success: function (data) {
                if (data.code == 0) {
                    $$(document).find('#orderData ul').append(data.data);
                    loading = false;
                } else if (data.code == 1) {
                    // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    // Remove preloader
                    $$('.infinite-scroll-preloader').remove();
                    return;
                } else {
                    return false;
                }
            },
            error:function(){
                myApp.detachInfiniteScroll($$('.infinite-scroll'));
                // Remove preloader
                $$('.infinite-scroll-preloader').remove();
                loading = false;
                i--;
            }
        });
        i++;
    });
}


// Initialize your app
var myApp = new Framework7({
    cache: false,
    modalTitle: '提示'
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    dynamicNavbar: true
});

$$(document).on('pageBeforeAnimation', function (e) {

    var page = e.detail.page;

    $$('.cart').addClass('hidden');
    $$('.toolbar-inner a').removeClass('active');
    var typeID = page.url;
    typeID = typeID.replace("?typeID=","");

    //关闭地址选择器
    if (pickerAddress) {
        pickerAddress.close();
    }
    if (shopTime) {
        shopTime.close();
    }
    switch (page.name)
    {
        case 'index':
            $.getGoodsList(page.name, typeID);
            $$('#index').addClass('active');
            break;
        case 'list':
            $$('#list').addClass('active');
            break;
        case 'cart':
            if($address.length != 0)
            {
                var pickerAddress = myApp.picker({
                    input: '#picker-address',
                    cols: [
                        {
                            textAlign: 'center',
                            values: $address
                        }
                    ]
                });
                var shopTime = myApp.picker({
                    input: '#shop-time',
                    cols: [
                        {
                            textAlign: 'center',
                            values: ['12:20 - 12:50', '18:20 - 18:50', '21:20 - 21:50']
                        }
                    ]
                });
            }

            $$('.cart').removeClass('hidden');
            $$(page.container).find('.page-content').addClass('cart-content');
            $$('#cart').addClass('active');
            break;
        case 'user':
        case 'user-address':
        case 'user-address-add':
        case 'user-address-edit':
            ajaxGetAddress();
            $$('form.ajax-submit').on('form:success', function (e) {
                var data = JSON.parse(e.detail.data); // Ajax repsonse from action file
                if (data.code == 200)
                {
                    myApp.alert(data.msg);
                    mainView.router.loadPage(data.url);
                } else {
                    myApp.alert(data.msg);
                }
            });
            myApp.closeModal('.popup-pay');
            $$('#user').addClass('active');
            break;
        case 'user-order':
            $.getOrderList();
            myApp.closeModal('.popup-pay');
            $$('#user').addClass('active');
            break;
        default:
            $$('#index').addClass('active');
    }
    $.refreshJs(page.name);
});